package com.vtb.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.Weibo;
import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;

import com.vtb.base.VtbBaseServlet;
import com.vtb.entity.SsOauth;
import com.vtb.utils.DateUtils;

/**
 * 授权新浪微博
 * 
 * @author Chen Tao
 * @date 2012-7-9 下午3:44:08
 */
@SuppressWarnings("serial")
public class SsOauthServlet extends VtbBaseServlet {
    private static final Log log = LogFactory.getLog(SsOauthServlet.class);
    Oauth oauth = new Oauth();
    Users um = new Users();
    SsOauth ssOauth;
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        if (code == null && "".equals(code)) {
            response.sendRedirect("error?err_code=1002");
            return;
        }
        try {
            AccessToken accessToken = oauth.getAccessTokenByCode(code);
            Weibo weibo = new Weibo();
            weibo.setToken(accessToken.getAccessToken());
            User user = um.showUserById(accessToken.getUid());
            ssOauth = new SsOauth();
            ssOauth.setAccess_token(accessToken.getAccessToken());
            ssOauth.setExpires_in(accessToken.getExpireIn());
            ssOauth.setRefresh_token(accessToken.getRefreshToken());
            ssOauth.setNick(user.getScreenName());
            ssOauth.setCreateTime(DateUtils.createTime());
            ssOauth.setUser(new com.vtb.entity.User(user.getScreenName(), user.getProfileImageUrl()));
        } catch (WeiboException e) {
            log.error("获取新浪code失败：", e);
            response.sendRedirect("error?err_code=1002");
            throw new WtbException("获取新浪code失败"+e);
        }
        super.doSession(request, response);
        lastMap.put("ss", ssOauth);
        session.setAttribute("lastMap", lastMap);
        session.setAttribute("status", null);
        response.sendRedirect("last");
    }
}
